import re
from django.shortcuts import render_to_response
from django.template import RequestContext
from langutils import copy_func_attrs

def title(title):
    def decorator(view_func):
        view_func.title = title
        return view_func
    return decorator

def trace_sql(view_func):
    from django.db import connection
    replace_re = re.compile('(FROM|WHERE|ORDER BY)', re.I)

    def decorated(*args, **kwargs):
        res = view_func(*args, **kwargs)
        print '=== %s ===' % view_func.__name__
        for i, q in enumerate(connection.queries):
            sql = replace_re.sub('\n\g<1>', q['sql'])
            print '[ %01.d ]\n%s\n' % (i, sql)
        return res
    decorated.__dict__ = view_func.__dict__
    return decorated

def render_to(template, title=None):
    def decorator(view_func):
        if title:
            view_func.title = title
        def decorated(request, *args, **kwargs):
            context = view_func(request, *args, **kwargs)
            if not isinstance(context, dict):
                return context
            if title:
                context['title'] = title
            return render_to_response(template, context,
                context_instance=RequestContext(request))
        copy_func_attrs(view_func, decorated)
        return decorated
    return decorator

